<template>
  <div>
    <div class="taskCreate" v-if="showCreate">
      <van-form>
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6"
          v-model="taskInfo.taskName"
          type="text"
          autosize
          label="作业名称"
        />
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6"
          v-model="show.beginTime_plan"
          label="开始时间"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="onclickBeginTimePlan"
        />
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6"
          v-model="show.endTime_plan"
          label="结束时间"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="onclickEndTimePlan"
        />
        <van-cell-group>
          <van-cell v-if="taskSetting.autoTimeControl && taskInfo.state !== 5" style="color:#646566" title="自动开始">
            <template #right-icon>
              <van-radio-group v-model="autoBegin" direction="horizontal">
                <van-radio name="0" icon-size="24px" style="font-size: 18px;">否</van-radio>
                <van-radio name="1" icon-size="24px" style="font-size: 18px;">是</van-radio>
              </van-radio-group>
            </template>
          </van-cell>
          <van-cell v-if="taskSetting.autoTimeControl && taskInfo.state !== 5" style="color:#646566" title="自动结束">
            <template #right-icon>
              <van-radio-group v-model="autoEnd" direction="horizontal">
                <van-radio name="0" icon-size="24px" style="font-size: 18px;">否</van-radio>
                <van-radio name="1" icon-size="24px" style="font-size: 18px;">是</van-radio>
              </van-radio-group>
            </template>
          </van-cell>
        </van-cell-group>
        <van-field
          v-if="taskSetting.autoTimeControl && permission.update.orderTime && taskInfo.state !== 5 && taskInfo.state !== 6"
          v-model="aheadTimeNumber"
          label="提前开始"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="aheadTime=true"
        />
        <van-field
          v-if="taskSetting.autoTimeControl && permission.update.orderTime"
          v-model="delayTimeNumber"
          label="延后结束"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="delayTime=true"
        />
        <van-field
          v-if="taskSetting.hasWorkArea && taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.workArea"
          v-model="show.workArea"
          label="作业地点"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="onclickWorkArea"
        />
        <van-field
          v-if="!taskSetting.hasWorkArea"
          v-model="taskInfo.workAreaComment"
          label="作业地点"
          type="textarea"
        />
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.workContent"
          v-model="taskInfo.workContent"
          label="作业内容"
          type="textarea"
        />
        <van-field
          v-if="taskSetting.hasFence && taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.fence && fenceIdReFresh"
          label="作业区域"
          placeholder="无"
          input-align="right"
          readonly
        >
          <template #input>
            <span v-if="!taskInfo.fenceId">
              <van-tag type="success" @click="onClickAutoFence">点击生成</van-tag>
            </span>
            <span v-else-if="taskInfo.fenceId">
              {{taskInfo.fenceId}}
              <van-tag type="danger" @click="onClickDelFence">删除</van-tag>
            </span>
            <span v-else></span>
          </template>
        </van-field>
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.roleSelect && taskSetting.haveWorkLeader"
          label="作业组长"
          input-align="right"
          readonly
          @click="onclickRole('workLeader')"
        >
          <template #button>
            <van-button
              v-if="!workLeader.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('workLeader')"
            >本人</van-button>
            <van-button v-if="!workLeader.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="workLeader.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.roleSelect"
          :label="taskSetting.showInformation.managerShowName"
          input-align="right"
          readonly
          @click="onclickRole('manager')"
        >
          <template #button>
            <van-button
              v-if="!manager.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('manager')"
            >本人</van-button>
            <van-button v-if="!manager.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="manager.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.roleSelect"
          label="联络员"
          input-align="right"
          readonly
          @click="onclickRole('liaison')"
        >
          <template #button>
            <van-button
              v-if="!liaison.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('liaison')"
            >本人</van-button>
            <van-button v-if="!liaison.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="liaison.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>
        <van-field
          label="防护员"
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.roleSelect"
          input-align="right"
          readonly
          @click="onclickRole('safeman')"
        >
          <template #button>
            <van-button
              v-if="!safeman.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('safeman')"
            >本人</van-button>
            <van-button v-if="!safeman.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="safeman.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>
        <van-field
          label="作业人员"
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6 && permission.update.roleSelect"
          input-align="right"
          readonly
          @click="onclickRole('worker')"
        >
          <template #button>
            <van-button
              v-if="!worker.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('worker')"
            >本人</van-button>
            <van-button v-if="!worker.length" size="small" plain type="warning">自定义</van-button>
            <van-button v-if="worker.length" size="small" plain type="warning">点击修改查看</van-button>
          </template>
        </van-field>
        <van-field
          v-if="taskInfo.state !== 5 && taskInfo.state !== 6"
          v-model="taskInfo.comment"
          type="textarea"
          autosize
          label="备注"
        />
        <van-popup v-model="showDateTimePicker" round position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="datetime"
            title="选择日期时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmDTP"
            @cancel="onCancelDTP"
          />
        </van-popup>
        <van-popup v-model="aheadTime" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="aheadTime = false"
            @confirm="onConfirmaheadTime"
          />
        </van-popup>
        <van-popup v-model="delayTime" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="delayTime = false"
            @confirm="onConfirmdelayTime"
          />
        </van-popup>
        <van-popup v-model="showWorkAreaPicker" round position="bottom" :style="{ height: '50%' }">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="workAreaPicker.secStationPicker.select"
              :options="workAreaPicker.secStationPicker.options"
              @change="onSecStationPickerChange"
            />
            <van-dropdown-item
              v-if="showSectionPicker"
              v-model="workAreaPicker.sectionPicker.select"
              :options="workAreaPicker.sectionPicker.options"
              @change="onSectionPickerChange"
            />
            <van-dropdown-item
              v-if="showUpDownPicker"
              v-model="workAreaPicker.upDownPicker.select"
              :options="workAreaPicker.upDownPicker.options"
              @change="onUpDownPickerChange"
              disabled
            />
            <van-dropdown-item
              v-if="showStationPicker"
              v-model="workAreaPicker.stationPicker.select"
              :options="workAreaPicker.stationPicker.options"
              @change="onStationPickerChange"
            />
            <van-dropdown-item
              v-if="showAreaTypePicker"
              v-model="workAreaPicker.areaTypePicker.select"
              :options="workAreaPicker.areaTypePicker.options"
              @change="onAreaTypePickerChange"
            />
            <van-dropdown-item
              v-if="showTrackPicker"
              v-model="workAreaPicker.trackPicker.select"
              :options="workAreaPicker.trackPicker.options"
              @change="onTrackPickerChange"
            />
            <van-dropdown-item
              v-if="showSignalPicker"
              v-model="workAreaPicker.signalPicker.select"
              :options="workAreaPicker.signalPicker.options"
              @change="onSignalPickerChange"
            />
            <van-dropdown-item
              v-if="showSwithchTrackPicker"
              v-model="workAreaPicker.switchTrackPicker.select"
              :options="workAreaPicker.switchTrackPicker.options"
              @change="onSwitchTrackPickerChange"
            />
          </van-dropdown-menu>
          <div class="workArea">
            <van-form>
              <van-row>
                <van-col span="14">
                  <van-field
                    v-model="taskInfo.workAreaKM.start.kilo"
                    name="a"
                    class="kilo"
                    label="开始 公里(K)"
                    placeholder="请填写"
                  />
                </van-col>
                <van-col span="10">
                  <van-field
                    v-model="taskInfo.workAreaKM.start.meter"
                    name="b"
                    class="meter"
                    label="米(M)"
                    placeholder="请填写"
                  />
                </van-col>
              </van-row>
              <van-row>
                <van-col span="14">
                  <van-field
                    v-model="taskInfo.workAreaKM.end.kilo"
                    name="c"
                    class="kilo"
                    label="结束 公里(K)"
                    placeholder="请填写"
                  />
                </van-col>
                <van-col span="10">
                  <van-field
                    v-model="taskInfo.workAreaKM.end.meter"
                    name="d"
                    class="meter"
                    label="米(M)"
                    placeholder="请填写"
                  />
                </van-col>
              </van-row>
              <van-field
                v-model="taskInfo.workAreaComment"
                label="补充内容"
                name="comment"
                type="textarea"
                autosize
                placeholder="请填写"
              />
              <div class="submit-area">
                <van-button round style="width:120px;" @click="onCancelWorkArea">取消</van-button>
                <van-button round type="info" style="width:120px;" @click="onConfirmWorkarea">确定</van-button>
              </div>
            </van-form>
          </div>
        </van-popup>
        <div class="submit-area">
          <van-button round style="width:120px;" @click="onCancelTaskCreate">取消</van-button>
          <van-button round type="info" style="width:120px;" @click="onSubmitTaskCreate">修改</van-button>
        </div>
      </van-form>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
import { getFormatDate, getFormatHourMinute, getFormatDateTime } from '../../utils/datetime'
import { getLineData, getSectionData } from '@/api/line_data'
import { mapGetters, createNamespacedHelpers } from 'vuex'
import { createFenceByTrackNo, deleteFenceByIds } from '../../api/fence'
import { getUserInfobyId, getDeviceInfobyId } from '../../api/userDeviceGroup'
import { convertUserInfoStruct, convertDeviceInfoStruct } from '../../utils/taskUtils'
const taskCreateStore = createNamespacedHelpers('taskCreate')
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      delayTimeNumber: '',
      aheadTimeNumber: '',
      columns: ['无', '五分钟', '十分钟', '十五分钟', '二十分钟', '二十五分钟', '三十分钟', '无'],
      aheadTime: false,
      delayTime: false,
      autoBegin: '0',
      autoEnd: '0',
      lineData: null,
      initTaskInfo: false,
      fenceIdReFresh: true,
      sectionData: null,
      taskInfo: {
        taskName: '',
        fenceId: 0,
        beginTime_plan: 0,
        endTime_plan: 0,
        workAreaKM: {
          start: { kilo: '', meter: '' },
          end: { kilo: '', meter: '' }
        },
        workAreaComment: '',
        workContent: '',
        comment: ''
      },
      show: {
        beginTime_plan: '',
        endTime_plan: '',
        workArea: '',
        fence: ''
      },
      showDateTimePicker: false,
      showWorkAreaPicker: false,
      curShow: '',
      minDate: new Date(2022, 1, 1),
      maxDate: new Date(2025, 12, 31),
      currentDate: new Date(),
      showStationPicker: false,
      showTrackPicker: false,
      showSectionPicker: false,
      showUpDownPicker: false,
      workAreaPicker: {
        secStationPicker: {
          select: 0,
          options: [
            { text: '选择车站区间', value: 0 },
            { text: '站内', value: 1 },
            { text: '区间', value: 2 }
          ]
        },
        stationPicker: { select: 0, options: [{ text: '选择车站', value: 0 }] },
        trackPicker: { select: 0, options: [{ text: '选择轨道', value: 0 }] },
        signalPicker: { select: 0, options: [{ text: '选择信号机', value: 0 }] },
        switchTrackPicker: { select: 0, options: [{ text: '选择道岔区段', value: 0 }] },
        sectionPicker: { select: 0, options: [{ text: '选择区间', value: 0 }] },
        areaTypePicker: {
          select: 0,
          options: [
            { text: '选择地点类型', value: 0 },
            { text: '股道', value: 1 },
            { text: '信号机', value: 2 },
            { text: '道岔', value: 3 },
            { text: '道岔区段', value: 4 }
          ]
        },
        upDownPicker: {
          select: 0,
          options: [
            { text: '选择上下行', value: 0 },
            { text: '上行', value: 1 },
            { text: '下行', value: 2 }
          ]
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId', 'permission', 'taskSetting']),
    ...taskCreateStore.mapGetters(['showCreate', 'manager', 'workLeader', 'liaison', 'safeman', 'worker', 'workLeaderShow', 'managerShow', 'liaisonShow', 'safemanShow', 'workerShow'])
  },
  watch: {},
  created() {
    if (this.$route.query.taskInfo && !this.initTaskInfo) {
      this.initTaskInfo = true
      this.taskInfo = this.$route.query.taskInfo
      this.taskInfo.fenceId = this.$route.query.taskInfo.fenceIds[0]
      if (!this.taskInfo.workAreaKM) {
        this.taskInfo.workAreaKM = {
          start: { kilo: '', meter: '' },
          end: { kilo: '', meter: '' }
        }
      }
      this.show.beginTime_plan = this.getData(this.$route.query.taskInfo.beginTime_plan)
      this.show.endTime_plan = this.getData(this.$route.query.taskInfo.endTime_plan)
      this.show.workArea = this.generateWorkareaShow2()
      this.show.fence = this.$route.query.taskInfo.fenceIds
    }
  },
  mounted() {
    this.setTaskCreateData({ key: 'manager', value: this.$route.query.taskInfo.manager })
    this.setTaskCreateData({ key: 'workLeader', value: this.$route.query.taskInfo.workLeader })
    this.setTaskCreateData({ key: 'liaison', value: this.$route.query.taskInfo.liaison })
    this.setTaskCreateData({ key: 'safeman', value: this.$route.query.taskInfo.safeman })
    this.setTaskCreateData({ key: 'worker', value: this.$route.query.taskInfo.worker })
    this.fillTaskCreateData()
  },
  methods: {
    ...taskCreateStore.mapMutations(['setShowCreate', 'setTaskCreateData']),
    getPickedStationNo() {
      return parseInt(this.workAreaPicker.stationPicker.select)
    },
    getPickedTrackId() {
      return parseInt(this.workAreaPicker.trackPicker.select)
    },
    getPickedTrackName() {
      for (var i in this.workAreaPicker.trackPicker.options) {
        if (this.workAreaPicker.trackPicker.options[i].value === this.workAreaPicker.trackPicker.select) {
          return this.workAreaPicker.trackPicker.options[i].text
        }
      }
      return 0
    },
    getPickedSignalId() {
      return parseInt(this.workAreaPicker.signalPicker.select)
    },
    getPickedSignalName() {
      for (var i in this.workAreaPicker.signalPicker.options) {
        if (this.workAreaPicker.signalPicker.options[i].value === this.workAreaPicker.signalPicker.select) {
          return this.workAreaPicker.signalPicker.options[i].text
        }
      }
      return 0
    },
    getPickedSwitchId() {
      return parseInt(this.workAreaPicker.switchPicker.select)
    },
    getPickedSwitchName() {
      for (var i in this.workAreaPicker.switchPicker.options) {
        if (this.workAreaPicker.switchPicker.options[i].value === this.workAreaPicker.switchPicker.select) {
          return this.workAreaPicker.switchPicker.options[i].switchTrack
        }
      }
      return 0
    },
    getPickedSwitchTrackId() {
      return parseInt(this.workAreaPicker.switchTrackPicker.select)
    },
    getPickedSwitchTrackName() {
      for (var i in this.workAreaPicker.switchTrackPicker.options) {
        if (this.workAreaPicker.switchTrackPicker.options[i].value === this.workAreaPicker.switchTrackPicker.select) {
          return this.workAreaPicker.switchTrackPicker.options[i].text
        }
      }
      return 0
    },
    async onClickAutoFence() {
      try {
        var trackId
        var trackName
        const stationNo = this.getPickedStationNo() // 车站
        if (this.showTrackPicker) {
          trackId = this.getPickedTrackId() // 股道
          trackName = this.getPickedTrackName() // 股道名字
        } else if (this.showSignalPicker) {
          trackId = this.getPickedSignalId() // 股道
          trackName = this.getPickedSignalName() // 股道名字
        } else if (this.showSwitchPicker) {
          trackId = this.getPickedSwitchId() // 股道
          trackName = this.getPickedSwitchName() // 股道名字
        } else if (this.showSwitchTrackPicker) {
          trackId = this.getPickedSwitchTrackId() // 股道
          trackName = this.getPickedSwitchTrackName() // 股道名字
        }
        var msg
        const fenceType = 1 // 封闭作业区域
        if (this.showSignalPicker) {
          msg = await createFenceByTrackNo(1, stationNo, trackId, fenceType, trackName, 'signal')
        } else {
          msg = await createFenceByTrackNo(1, stationNo, trackId, fenceType, trackName, 'track')
        }
        this.fenceIdReFresh = false
        this.taskInfo.fenceId = parseInt(msg.data.fence_id)
        // this.show.fence = `作业区域(id:${msg.data.fence_id})`
        this.$toast(`生成作业区域成功，id:${msg.data.fence_id}`)
        setTimeout(() => {
              this.fenceIdReFresh = true
            }, 500)
      } catch (err) {
        this.$toast(`生成作业区域失败：${err}`)
      }
    },
    async onClickDelFence() {
      try {
        const fenceId = this.taskInfo.fenceId
        if (fenceId) {
          const msg = await deleteFenceByIds([fenceId])
          if (msg.code === 0) {
            this.taskInfo.fenceId = 0
            this.fenceIdReFresh = false
            // this.show.fence = ''
            this.$toast(`删除作业区域成功，id:${fenceId}`)
            setTimeout(() => {
              this.fenceIdReFresh = true
            }, 500)
          }
        } else {
          this.$toast('删除作业区域失败：找不到fenceId')
        }
      } catch (err) {
        this.$toast(`删除作业区域失败：${err}`)
      }
    },
    getData(n) {
      const now = new Date(n)
      const y = now.getFullYear()
      const m = now.getMonth() + 1
      const d = now.getDate()
      const hour = now.getHours()
      const minute = now.getMinutes()
      return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute)
    },
    async onChooseMyDevice(role) {
      const deviceMsg = await getDeviceInfobyId(this.deviceId)
      if (deviceMsg.code === 0) {
        const members = []
        members.push(convertDeviceInfoStruct(deviceMsg.data))
        this.setTaskCreateData({ key: role, value: members })
      }
    },
    async onChooseMyUser(role) {
      const userMsg = await getUserInfobyId(this.userId)
      if (userMsg.code === 0) {
        const members = []
        members.push(convertUserInfoStruct(userMsg.data))
        this.setTaskCreateData({ key: role, value: members })
      }
    },
    jumpToMemberSelect(role, chosenItems) {
      this.setShowCreate(false)
      this.$router.push({ path: '/memberSelectGWU', query: { role, chosenItems } })
    },
    fillTaskCreateData() {
      this.taskInfo.type = 1
      this.fillShowData(this.taskInfo)
    },
    fillShowData(taskInfo) {
      // workArea Show
      this.show.workArea = this.generateWorkareaShow()
    },
    onclickBeginTimePlan() {
      this.showDateTimePicker = true
      this.curShow = 'beginTimePlanPicker'
    },
    onclickEndTimePlan() {
      this.showDateTimePicker = true
      this.curShow = 'endTimePlanPicker'
    },
    onclickRole(role) {
      this.jumpToMemberSelect(role, this[role])
    },
    onclickFence() {},
    async onclickWorkArea() {
      this.showWorkAreaPicker = true
      if (!this.lineData) {
        try {
          const msg = await getLineData()
          if (msg.code === 0) {
            this.lineData = msg.data
            this.setStationOptions()
          } else {
            throw new Error('Line Data Error')
          }
        } catch (err) {
          console.log(err)
        }
      }
      if (!this.sectionData) {
        try {
          const msg = await getSectionData()
          if (msg.code === 0) {
            this.sectionData = msg.data
            this.setSectionOptions()
          } else {
            throw new Error('Section Data Error')
          }
        } catch (err) {
          console.log(err)
        }
      }
      // TODO 二次打开时的渲染？
      // if (this.workAreaPicker.stationPicker.select) {
      //   // 选择了具体车站
      //   this.setTrackOptions(this.workAreaPicker.stationPicker.select)
      // }
    },
    setStationOptions() {
      for (const id in this.lineData) {
        this.workAreaPicker.stationPicker.options.push({ text: this.lineData[id].baseInfo.stationName, value: parseInt(this.lineData[id].baseInfo.stationNo) })
      }
    },
    setSectionOptions() {
      for (const id in this.sectionData) {
        this.workAreaPicker.sectionPicker.options.push({ text: this.getSectionText(this.sectionData[id].stations), value: parseInt(this.sectionData[id].sectionId) })
      }
    },
    setTrackOptions(stationNo) {
      const initArray = [{ text: '请选择轨道', value: 0 }]
      const optionsArray = Array.from(this.lineData[stationNo].tracks, (track) => {
        return { text: track.name, value: parseInt(track.id) }
      })
      this.workAreaPicker.trackPicker.options = initArray.concat(optionsArray)
    },
    setSignalOptions(stationNo) {
      const initArray = [{ text: '请选择信号机', value: 0 }]
      const optionsArray = Array.from(this.lineData[stationNo].signals, (signal) => {
        return { text: signal.name, value: parseInt(signal.id) }
      })
      this.workAreaPicker.signalPicker.options = initArray.concat(optionsArray)
    },
    setSwitchTrackOptions(stationNo) {
      for (var i = 0; i < this.lineData[stationNo].switchTracks.length; i++) {
        this.workAreaPicker.switchTrackPicker.options.push({ text: this.lineData[stationNo].switchTracks[i], value: i + 1 })
      }
    },
    getSectionText(stations) {
      if (stations instanceof Array && stations.length === 2) {
        return `${stations[0].stationName}~${stations[1].stationName}`
      } else {
        return ''
      }
    },
    onConfirmaheadTime(value) {
      this.aheadTimeNumber = value
      this.aheadTime = false
    },
    onConfirmdelayTime(value) {
      this.delayTimeNumber = value
      this.delayTime = false
    },
    onConfirmDTP(dateTime) {
      if (this.curShow === 'beginTimePlanPicker') {
        this.taskInfo.beginTime_plan = dateTime
        this.show.beginTime_plan = getFormatDate(dateTime) + ' ' + getFormatHourMinute(dateTime)
      } else if (this.curShow === 'endTimePlanPicker') {
        this.taskInfo.endTime_plan = dateTime
        this.show.endTime_plan = getFormatDate(dateTime) + ' ' + getFormatHourMinute(dateTime)
      }
      this.showDateTimePicker = false
    },
    onCancelDTP() {
      this.showDateTimePicker = false
    },
    onSecStationPickerChange(val) {
      if (val === 0) {
        this.showStationPicker = false
        this.showTrackPicker = false
        this.showSectionPicker = false
        this.showUpDownPicker = false
      } else if (val === 1) {
        this.showStationPicker = true
        this.showTrackPicker = false
        this.showSectionPicker = false
        this.showUpDownPicker = false

        this.workAreaPicker.stationPicker.select = 0
      } else if (val === 2) {
        this.showStationPicker = false
        this.showTrackPicker = false
        this.showSectionPicker = true
        this.showUpDownPicker = true

        this.workAreaPicker.sectionPicker.select = 0
      } else {
      }
    },
    onStationPickerChange(stationNo) {
      if (stationNo === 0) {
        this.showAreaTypePicker = false
      } else {
        this.showAreaTypePicker = true
        this.setTrackOptions(stationNo)
        this.setSignalOptions(stationNo)
        this.setSwitchTrackOptions(stationNo)
      }
    },
    onAreaTypePickerChange(val) {
      if (val === 0) {
        this.showTrackPicker = false
        this.showSignalPicker = false
        this.showSwithchTrackPicker = false
      } else if (val === 1) {
        this.showTrackPicker = true
        this.showSignalPicker = false
        this.showSwithchTrackPicker = false
      } else if (val === 2) {
        this.showTrackPicker = false
        this.showSignalPicker = true
        this.showSwithchTrackPicker = false
      } else if (val === 3) {
        this.showTrackPicker = false
        this.showSignalPicker = false
        this.showSwithchTrackPicker = true
      }
    },
    onSectionPickerChange(val) {},
    onUpDownPickerChange(val) {},
    onTrackPickerChange(val) {},
    onSignalPickerChange(val) {},
    onSwitchTrackPickerChange(val) {},
    generateWorkareaShow() {
      let showStr = ''
      const type = this.workAreaPicker.secStationPicker.select // 站内、区间
      if (type === 1) {
        const stationNo = this.workAreaPicker.stationPicker.select
        if (stationNo) {
          const idx = this.workAreaPicker.stationPicker.options.findIndex((item) => item.value === stationNo)
          showStr = `站内：[${this.workAreaPicker.stationPicker.options[idx].text}]`
        }
      } else if (type === 2) {
        const sectionId = this.workAreaPicker.sectionPicker.select
        if (sectionId) {
          const idx = this.workAreaPicker.sectionPicker.options.findIndex((item) => item.value === sectionId)
          showStr = `区间：[${this.workAreaPicker.sectionPicker.options[idx].text}]`
        }
      } else {
      }
      return showStr
    },
    async generateWorkareaShow2() {
      let showStr = ''
      {
        await this.onclickWorkArea()
        this.showWorkAreaPicker = false
        this.onStationPickerChange(parseInt(this.taskInfo.workArea.places[0].stationNo))
        this.workAreaPicker.stationPicker.select = this.taskInfo.workArea.places[0].stationNo
        this.workAreaPicker.secStationPicker.select = 1
        this.showStationPicker = true
        this.showAreaTypePicker = true
        if (this.taskInfo.workArea.places[0].type === 'track') {
          this.workAreaPicker.areaTypePicker.select = 1
          this.showTrackPicker = true
          this.workAreaPicker.trackPicker.select = this.taskInfo.workArea.places[0].id
        } else if (this.taskInfo.workArea.places[0].type === 'signal') {
          this.workAreaPicker.areaTypePicker.select = 2
          this.showSignalPicker = true
          this.workAreaPicker.signalPicker.select = this.taskInfo.workArea.places[0].id
        } else if (this.taskInfo.workArea.places[0].type === 'switchTrack') {
          this.workAreaPicker.areaTypePicker.select = 3
          this.showSwithchTrackPicker = true
          this.workAreaPicker.switchTrackPicker.select = this.taskInfo.workArea.places[0].id
        }
        const stationNo = this.taskInfo.workArea.places[0].stationNo
        if (stationNo) {
          showStr = '站内：'
        }
        this.onConfirmWorkarea()
      }
      return showStr
    },
    onConfirmWorkarea() {
      const type = this.workAreaPicker.secStationPicker.select // 站内、区间
      do {
        if (type === 1) {
          if (this.workAreaPicker.stationPicker.select === 0) {
            this.$toast('请选择车站')
            break
          }
        } else if (type === 2) {
          if (this.workAreaPicker.sectionPicker.select === 0) {
            this.$toast('请选择区间')
            break
          }
        } else {
          this.$toast('请选择车站区间')
          break
        }
        this.show.workArea = this.generateWorkareaShow()
        this.showWorkAreaPicker = false
      } while (0)
    },
    onCancelWorkArea() {
      this.showWorkAreaPicker = false
    },
    async onSubmitTaskCreate() {
      try {
        const msg = await getLineData()
        if (msg.code === 0) {
          this.lineData = msg.data
          this.setStationOptions()
        } else {
          throw new Error('Line Data Error')
        }
      } catch (err) {
        console.log(err)
      }
      if (!this.taskInfo.workAreaKM.start.kilo) {
        this.taskInfo.workAreaKM.start.kilo = null
      }
      if (!this.taskInfo.workAreaKM.start.meter) {
        this.taskInfo.workAreaKM.start.meter = null
      }
      if (!this.taskInfo.workAreaKM.end.kilo) {
        this.taskInfo.workAreaKM.end.kilo = null
      }
      if (!this.taskInfo.workAreaKM.end.meter) {
        this.taskInfo.workAreaKM.end.meter = null
      }
      var task = {
        type: 1,
        state: 3,
        taskName: this.taskInfo.taskName,
        autoBegin: parseInt(this.sautoBegin),
        autoEnd: parseInt(this.autoEnd),
        beginTime_order: '',
        terminateTime_order: '',
        beginTime_plan: this.show.beginTime_plan,
        endTime_plan: this.show.endTime_plan,
        workLeader: [],
        manager: [],
        liaison: [],
        safeman: [],
        worker: [],
        workArea: {
          places: [],
          areaKM: this.taskInfo.workAreaKM,
          areaDescription: this.taskInfo.workAreaComment
        },
        workContent: this.taskInfo.workContent,
        fenceIds: this.taskInfo.fenceId ? [this.taskInfo.fenceId] : [],
        comment: this.taskInfo.comment
      }
      var aheadTimeList = { 无: 0, 五分钟: 1, 十分钟: 2, 十五分钟: 3, 二十分钟: 4, 二十五分钟: 5, 三十分钟: 6 }
      if (this.aheadTimeNumber) {
        task.beginTime_order = getFormatDateTime(new Date(this.taskInfo.beginTime_plan - aheadTimeList[this.aheadTimeNumber] * 60 * 5 * 1000))
      } else task.beginTime_order = task.beginTime_plan
      if (this.delayTimeNumber) {
        task.terminateTime_order = getFormatDateTime(new Date(this.taskInfo.endTime_plan + aheadTimeList[this.delayTimeNumber] * 60 * 5 * 1000))
      } else task.terminateTime_order = task.endTime_plan
      if (this.workAreaPicker.secStationPicker.select === 1) {
        const stationNo = parseInt(this.workAreaPicker.stationPicker.select)
        if (stationNo) {
          var name = ''
          var type = ''
          var id = ''
          const areaType = parseInt(this.workAreaPicker.areaTypePicker.select)
          if (areaType === 1) {
            id = parseInt(this.workAreaPicker.trackPicker.select)
            if (id) {
              const index = this.lineData[stationNo].tracks.findIndex((item) => parseInt(item.id) === id)
              if (index >= 0) {
                type = 'track'
                name = this.lineData[stationNo].tracks[index].name
              }
            }
          }
          if (areaType === 2) {
            id = parseInt(this.workAreaPicker.signalPicker.select)
            if (id) {
              const index = this.lineData[stationNo].signals.findIndex((item) => parseInt(item.id) === id)
              if (index >= 0) {
                type = 'signal'
                name = this.lineData[stationNo].signals[index].name
              }
            }
          }
          if (areaType === 3) {
            id = parseInt(this.workAreaPicker.switchTrackPicker.select)
            if (id) {
              type = 'switchTracks'
              name = this.lineData[stationNo].switchTracks[id - 1]
            }
          }
          const areaItem = { stationNo, id, name, type }
          task.workArea.places.push(areaItem)
        }
      }

      this.workLeader.forEach((item) => {
        task.workLeader.push({ type: item.type, id: item.id })
      })
      this.manager.forEach((item) => {
        task.manager.push({ type: item.type, id: item.id })
      })
      this.liaison.forEach((item) => {
        task.liaison.push({ type: item.type, id: item.id })
      })
      this.safeman.forEach((item) => {
        task.safeman.push({ type: item.type, id: item.id })
      })
      this.worker.forEach((item) => {
        task.worker.push({ type: item.type, id: item.id })
      })
      var task1
      if (this.taskInfo.state === 5 || this.taskInfo.state === 6) {
        task1 = task
        task = {
          terminateTime_order: task1.terminateTime_order
        }
      }
      const { data } = await this.$http.put(`/task/update?taskId=${this.$route.query.taskId}`, task)
      if (data.code === 0) {
        this.$toast('创建成功')
        this.$router.go(-1)
      } else {
        this.$toast(`创建失败${data.msg}`)
      }
    },
    onCancelTaskCreate() {
      this.$router.go(-1)
    }
    // getPostTaskWorker() {
    //   const worker = {}
    //   if (this.worker.type) {
    //     worker.id = this.worker.id
    //     worker.type = this.worker.type
    //     worker.name = this.worker.name
    //   }
    //   return worker
    // }
  }
}
</script>

<style lang="less" scoped>
.taskCreate {
  .workArea {
    .van-cell {
      font-size: 30px;
    }
    .van-form {
      .meter {
        /deep/.van-field__label {
          width: 90px;
        }
      }
      .kilo {
        /deep/.van-field__label {
          width: 192px;
        }
      }
    }
  }
  .submit-area {
    margin: 20px 100px;
    display: flex;
    justify-content: space-between;
  }
}
</style>
